﻿using AutoMapper;
using MediatR;
using StoreIModels;
using StoreISet.Applicationes.Command;
using StoreRepositorys.Impl;
using StoreRepositorys.Interface;

namespace StoreISet.Applicationes.CommandHandler
{
    public class StoreUpdateCommandHandler : IRequestHandler<StoreUpdateCommand ,int>
    {
        public IStoreRepository _IRepository;
        public IMapper _mapper;
        public IRelationshipStoreRepository _IRelationshipStoreRepository;
        public StoreUpdateCommandHandler(IStoreRepository storeRepository, IMapper mapper, IRelationshipStoreRepository relationshipStoreRepository)
        {
            _IRepository = storeRepository;
            _IRelationshipStoreRepository=relationshipStoreRepository;
            _mapper = mapper;
        }
        public async Task<int> Handle(StoreUpdateCommand request, CancellationToken cancellationToken)
        {
            StoreModel models = _mapper.Map<StoreModel>(request);
            var res = await _IRepository.Updateasync(models);
            var tolist = request.adderId.Split(',');
            var Restult = 0;
            var list=await _IRelationshipStoreRepository.GetAllAsync(x=>x.StoreId == request.StoreId);
            RelationshipStoreModels Remodels = new RelationshipStoreModels();
            foreach (var item in list)
            {
                await _IRelationshipStoreRepository.Deleteasync(item.Id);
            }
            foreach (var i in tolist)
            {

                Remodels.StoreId =request.StoreId;
                Remodels.AssortedId = Convert.ToInt32(i);
                Restult = await _IRelationshipStoreRepository.Addasync(Remodels);
            }
            return Restult;

        }
    }
}
